package com.lam.system.service.impl;

import java.text.MessageFormat;
import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lam.common.components.easyexcel.imp.model.AbstractImportBody;
import com.lam.common.components.easyexcel.imp.model.ImportEntry;
import com.lam.common.components.easyexcel.imp.model.ImportWrapper;
import com.lam.common.components.easyexcel.imp.service.AbstractImportService;
import com.lam.common.constant.CommonConstant;
import com.lam.common.constant.SystemConstant;
import com.lam.common.utils.StringUtils;
import com.lam.common.validate.ValidateUtil;
import com.lam.common.validate.model.UniqueDesc;
import com.lam.common.validate.model.ValidOperType;
import com.lam.system.entity.SysRole;
import com.lam.system.entity.imp.SysRoleImp;
import com.lam.system.mapper.SysRoleMapper;
import com.lam.system.param.SysRoleMenuParam;
import com.lam.system.param.SysRoleParam;
import com.lam.system.service.SysRoleMenuService;
import com.lam.system.service.SysRoleService;

/**
 * 角色配置Service业务层处理
 * 
 * @author admin
 * @date 2022-09-20
 */
@Service
public class SysRoleServiceImpl extends AbstractImportService<SysRoleImp, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * 查询角色配置
     * 
     * @param id ID
     * @return 单个对象
     */
    @Override
    @Transactional(readOnly = true)
    public SysRole selectById(String id) {

        return sysRoleMapper.selectById(id);
    }

    /**
     * 查询角色配置列表
     * 
     * @param param
     * @return 
     */
    @Override
    @Transactional(readOnly = true)
    public List<SysRole> selectList(SysRoleParam param) {
    
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        //关键字查询
        if(StringUtils.isNotBlank(param.getKeywords())) {
        	queryWrapper.and(wr->{
        		wr.or().like("role_name", param.getKeywords());
        		wr.or().like("role_code", param.getKeywords());
        	});
        }
        queryWrapper.like(StringUtils.isNotBlank(param.getRoleNameKey()), "role_name", param.getRoleNameKey());
        queryWrapper.eq(StringUtils.isNotBlank(param.getRoleName()), "role_name", param.getRoleName());
        queryWrapper.like(StringUtils.isNotBlank(param.getRoleCodeKey()), "role_code", param.getRoleCodeKey());
        queryWrapper.eq(StringUtils.isNotBlank(param.getRoleCode()), "role_code", param.getRoleCode());
        queryWrapper.eq(Objects.nonNull(param.getStatus()), "status", param.getStatus());

        return sysRoleMapper.selectList(queryWrapper);
    }
    
    /**
     * 查询角色列表
     * 
     * @param param
     * @return 
     */
    @Override
    @Transactional(readOnly = true)
    public List<SysRole> toSelectList(SysRoleParam param) {
    	
    	QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
    	switch (param.getSelectType()) {
    	//用户关联的角色
		case "userRole": 
        	queryWrapper.inSql("id", String.format("select role_id from sys_user_role where user_id='%s'", param.getUserId()));
			break;
		//用户添加角色的候选列表
		case "userToSelectRole": 
			queryWrapper.notInSql("id", String.format("select role_id from sys_user_role where user_id='%s'", param.getUserId()));
			break;

		default:break;
		}
    	
    	//关键字查询
        if(StringUtils.isNotBlank(param.getKeywords())) {
        	queryWrapper.and(wr->{
        		wr.or().like("role_name", param.getKeywords());
        		wr.or().like("role_code", param.getKeywords());
        	});
        }
        queryWrapper.eq("status", CommonConstant.STATUS_NORMAL_1);

        return sysRoleMapper.selectList(queryWrapper);
    }

    /**
     * 新增角色配置
     * 
     * @param sysRole 
     * @return 
     */
    @Override
    @Transactional
    public int insert(SysRole sysRole) {
    
        return sysRoleMapper.insert(sysRole);
    }

    /**
     * 修改角色配置
     * 
     * @param sysRole 
     * @return 
     */
    @Override
    @Transactional
    public int update(SysRole sysRole) {
    
    	sysRole.setRoleCode(null);
        return sysRoleMapper.updateById(sysRole);
    }

    /**
     * 删除角色配置信息
     * 
     * @param idStr ID，多个用逗号分隔
     * @return 
     */
    @Override
    @Transactional
    public int deleteById(String idStr) {
    	if(StringUtils.isBlank(idStr)) {
            return 0;
    	}
    	
        ValidateUtil.validDataUsed("sys_user_role", "role_id", idStr, "角色有关联用户数据，不可删除");
        
    	int n = 0;
    	for (String id : StringUtils.str2List(idStr)) {
            n += sysRoleMapper.deleteById(id);
            sysRoleMenuService.deleteByRoleId(id, SysRoleMenuParam.TYPE_ADM);
        }
        return n;
    }
    
    @Override
    @Transactional
    public void importData(ImportWrapper<SysRoleImp, SysRole> wrapper) {
        
    	UniqueDesc uniqueDesc = ValidateUtil.selectUniqueDesc(SystemConstant.UNIQUE_ROLE_CODE);
    	importData(wrapper, new AbstractImportBody<SysRoleImp, SysRole>() {
			@Override
			public SysRole selectRecord(ImportEntry<SysRoleImp, SysRole> entry) {
				return ValidateUtil.selectUniqueData(entry.getData(), ValidOperType.ADD, uniqueDesc, SysRole.class);
			}
			@Override
			public int insertData(SysRole data) {
				return insert(data);
			}
			@Override
			public int updateData(SysRole data) {
				return update(data);
			}
			@Override
			public String notUniqueMsg(ImportEntry<SysRoleImp, SysRole> entry) {
				return MessageFormat.format("角色编码【{0}】已存在", entry.getData().getRoleCode());
			}
    	});
    }
    
}
